<template>
    <PageTemplate>
    <div class="abp-progress-details" slot="content">

        <div class="container container-top" >
            <el-form  label-width="150px"  :model="stage" ref="stage" >
                <el-collapse v-model="showCollapse2" accordion>
                    <el-collapse-item name="1" class="search-collapse-title">
                        <template slot="title">
                            <span class="vertical-bar" style="margin:0;" ></span>
                            <font  class="collapse-content" >{{$t('cm.baseinfo')}}</font>
                        </template>
                        <div class="div-form">
                            <el-row>
                                <!--主题-->
                                <el-col :span="12">
                                    <el-form-item  :label="$t('pur.process_folio')"  prop="folio" >
                                        <el-input   size="small" class="form-input" v-model="capaCity.folio" :disabled="true" placeholder="提交后自动生成"></el-input>
                                    </el-form-item>
                                </el-col>
                                <!--流程名称-->
                                <el-col :span="12">
                                    <el-form-item :label="$t('pur.process_procChName')" >
                                        <el-input   size="small" class="form-input" v-model="flow_access.procChName" :disabled="true"></el-input>
                                    </el-form-item>
                                </el-col>
                            </el-row>
                        </div>
                    </el-collapse-item>
                </el-collapse>
                <el-collapse v-model="showCollapse" accordion>
                    <el-collapse-item name="1" class="search-collapse-title">
                        <template slot="title">
                            <span class="vertical-bar" style="margin:0;" ></span>
                            <font  class="collapse-content" >详细信息</font>
                        </template>

                        <div class="div-form">
                            <el-row>
                              <el-col :span="12">
                                    <!-- prop="planId" -->
                                    <el-form-item  label="能力建设年度计划"  required>
                                        <el-select
                                          v-if="(planList && planList.length != 0) || !(isProgress || type =='approve' || type =='draftEdit'||type =='done')"
                                          class="form-input"
                                          v-model="stage.planId"
                                          @change="planSelectChange"
                                          size="small"
                                          :placeholder="$t('fe.pselect')" >
                                                <el-option
                                                  v-for="item in planList"
                                                  :label="item.planName"
                                                  :value="item.id"
                                                  :key="item.id">
                                                </el-option>
                                        </el-select>
                                        <span v-else>{{capaCity.planName}}</span>
                                     </el-form-item>
                                </el-col>
                            </el-row>
                            <el-row>
                            <!--  <el-col :span="12">
                                    <el-form-item  label="计划阶段"  prop="phaseId" :rules="rules">
                                        <span v-if="type==='look'|| type==='approve'||type =='draftEdit'||type =='done'">{{phase.phaseName}}</span>
                                        <el-select
                                          v-else
                                          class="form-input"
                                          v-model="stage.phaseId"
                                          @change="progressSelectChange"
                                          size="small"
                                          :placeholder="$t('fe.pselect')" >
                                            <el-option
                                              v-for="item in progressList"
                                              :label="item.phaseName"
                                              :value="item.id"
                                              :key="item.id">
                                            </el-option>
                                        </el-select>
                                    </el-form-item>
                                </el-col>  -->
                            </el-row>
                      <!--    <div
                            v-for="item in progressList"
                            :key="item.id"
                            :label="item"
                            :value="item.id">
                            <span>{{item}}</span>
                          </div> -->


                          <el-table
                            class="table"
                            border
                            ref="multipleTable"
                            :data="progressList"
                            tooltip-effect="dark"
                            style="width: 100%"
                            :show-overflow-tooltip="true"
                            :header-cell-style="{background:tableHeaderBGC}"
                          >
                            <el-table-column align="center" type="selection" width="60"></el-table-column>
                            <el-table-column type="index" :index="indexMethod" :label="$t('cm.no')" align="center" width="60" fixed></el-table-column>

                            <el-table-column prop="phaseName" label="阶段" align="center"></el-table-column>
                            <el-table-column prop="jdMb" label="阶段目标" align="center"></el-table-column>
                            <el-table-column prop="startTime" :formatter="dateFormatstart" label="开始日期" align="center"></el-table-column>
                            <el-table-column prop="endTime" :formatter="dateFormatend" label="结束日期" align="center"></el-table-column>
                            <el-table-column prop="stageProgress" label="阶段进展" align="center"></el-table-column>
                            <el-table-column :label="$t('cm.operate')" prop="statussss" fixed="right" align="center" width="140">
                              <template slot-scope="scope">
                                <ListBtn
                                  :options="btns"
                                  :row-data="scope.row"
                                  @triggerListBtn="handleListBtn"
                                >
                                </ListBtn>
                              </template>
                            </el-table-column>
                          </el-table>


              <el-collapse v-model="showCollapse3" accordion>
                <el-collapse-item name="1" class="search-collapse-title">
                  <template slot="title">
                    <span class="vertical-bar" style="margin:0;" ></span>
                    <font  class="collapse-content" >阶段信息</font>
                  </template>

                  <div v-if="stage.phaseId|| type=='approve'|| type =='draftEdit'||type =='done'"  >
                                <el-row v-if="false">
                                    <el-col :span="12" >
                                        <el-form-item label="能建项目名称" prop="processName">
                                            <span>{{capaCity.processName}}</span>
                                        </el-form-item>
                                    </el-col>
                                    <el-col :span="12">
                                        <el-form-item  label="年度"  prop="year" >
                                            <span>{{capaCity.year}}</span>
                                        </el-form-item>
                                    </el-col>
                                    <el-col :span='12'>
                                        <el-form-item label="负责人" prop="leadingmanName">
                                            <span>{{capaCity.leadingmanName}}</span>
                                        </el-form-item>
                                    </el-col>
                                    <el-col :span="12">
                                        <el-form-item label="项目目标" prop="projectTarget">
                                            <span>{{capaCity.projectTarget}}</span>
                                        </el-form-item>
                                    </el-col>
                                </el-row>
                                <el-row>
                                    <el-col :span="12">
                                        <el-form-item label="阶段" prop="phaseName">
                                            <span>{{phase.phaseName}}</span>
                                        </el-form-item>
                                    </el-col>
                                    <el-col :span="12">
                                        <el-form-item  label="开始日期"  prop="startTime">
                                            <span>{{phase.startTime | dateFormatType}}</span>
                                        </el-form-item>
                                    </el-col>
                                    <el-col :span='12'>
                                        <el-form-item label="结束日期" prop="endTime">
                                            <span>{{phase.endTime | dateFormatType}}</span>
                                        </el-form-item>
                                    </el-col>
                                    <el-col :span="12">
                                        <el-form-item label="阶段目标" prop="jdMb">
                                            <span>{{phase.jdMb}}</span>
                                        </el-form-item>
                                    </el-col>
                                </el-row>
                                <el-row>
                                  <el-col :span="24">
                                        <el-form-item label="阶段进展" prop="stageProgress" :rules="rules">
                                            <span v-if="!edit">{{phase.stageProgress}}</span>
                                            <el-input v-else  class="form-input" v-model="stage.stageProgress" type="textarea" :rows="4" size="small" placeholder="500个汉字以内" maxlength="500" show-word-limit></el-input>
                                        </el-form-item>
                                    </el-col>
                                </el-row>
                                <el-row>
                                    <el-col :span="10">
                                      <el-form-item label="阶段成果" prop="stageResultFileId" >
                                        <span v-if="!edit">{{phase.stageResultFileName}}</span>
                                        <FileUploadCommon
                                        v-else
                                        @uploadSuccess="uploadSuccess"
                                        @uploadRemove="uploadRemove"
                                        :fileList="phaseFileList"
                                        :limit="1">
                                        </FileUploadCommon>
                                        </el-form-item>
                                    </el-col>
                                </el-row>
                          </div>
                </el-collapse-item>
              </el-collapse>
                        </div>

                    </el-collapse-item>
                </el-collapse>
                <!--流程部分-->
                <el-collapse v-model="showCollapse1" accordion v-if="type !='look'&&type !='done'">
                    <el-collapse-item name="1" class="search-collapse-title">
                        <template slot="title">
                            <span class="vertical-bar" style="margin:0;" ></span>
                            <font  class="collapse-content" >{{$t('fe.procDeal')}}</font>
                        </template>
                        <div>
                            <procApprove :isStartAct="isStartAct" :procObj="flowDetails" :flow_access="flow_access" ></procApprove>
                        </div>
                    </el-collapse-item>
                </el-collapse>
                <!--流程部分 我的已办-->
                <el-collapse v-model="showCollapse1" accordion v-if="type =='done'">
                    <el-collapse-item name="1" class="search-collapse-title">
                        <template slot="title">
                            <span class="vertical-bar" style="margin:0;" ></span>
                            <font  class="collapse-content" >{{$t('fe.procDeal')}}</font>
                        </template>
                        <div>
                          <!--当前处理环节-->
                          <el-row class="flow-detail-row">
                            <el-col :span="4" class="flow-detail-col1" >{{$t('ndt.now_deal_actor')}} <span>&nbsp;</span></el-col>
                            <el-col :span="6" class="flow-detail-col2">{{flow_access.act_name}}</el-col>
                          </el-row>
                          <!--处理结论-->
                          <!--下一步处理环节-->
                          <el-row class="flow-detail-row">
                            <el-col :span="4" class="flow-detail-col1" >处理人</el-col>
                            <el-col :span="6" class="flow-detail-col2">
                              {{flow_access.approveMan}}
                            </el-col>
                          </el-row>
                          <!--下一步处理人-->
                          <!--抄送-->
                          <!--处理结论-->
                        </div>
                    </el-collapse-item>
                </el-collapse>
            </el-form>
        </div>
        <el-row class="row-empty-30"></el-row>
        <!-- 固定按钮的位置 -->
        <!--使用组件的方式来进行-->
        <fixedbutton v-if="type !='look' && type !='done'">
            <div slot="fixbtn">
                <el-button class="btn-default" type="primary" size="small" @click="saveProcHandle" >{{$t('cm.commit')}}</el-button>
                <el-button v-if="type == 'add' || type == 'draftEdit'" class="btn-default" type="primary" size="small" @click="saveDraftHandle">{{$t('cm.savedraft')}}</el-button>
            </div>
        </fixedbutton>
    </div>
    </PageTemplate>
</template>

<script>
import PageTemplate from '@/components/common/PageTemplate'
import {
    getStartAct,
    insertwin,
    delFile,
    addDraft,
    getNextApprovePerson,
    getBpmPscActInfo,
    getWFConfigActivity,
    getWFConfigProcID} from '@/api/api.js'
import PersonSelect from '@/components/asc/PersonSelect'
import ListBtn from '@/components/btn/ListBtn'
import procApprove from '@/components/common/procApprove'
import fixedbutton from '@/components/common/fixedbutton'
import download from '@/components/common/download'
import FileUploadCommon from '@/components/common/FileUploadCommon'
import store from '@/store'
import {
    COMMON
} from '@/utils/commonUtil'
import PurProcessDemWithinFileList from '@/components/purchase/PurProcessDemWithinFileList'
import {
    mapState,
    mapActions
} from 'vuex'
import * as Constant from '@/utils/constant'
import {
    ALERT
} from '@/utils/responseHandle'
import api_pur from '@/api/api_pur'
import sys_manage from '@/api/sys_manage'
import api_sri from '@/api/api_sri'
export default {
    components: {
        PageTemplate,
        PersonSelect,
        ListBtn,
        procApprove,
        fixedbutton,
        download,
        PurProcessDemWithinFileList,
        FileUploadCommon,
    },
    props: {
        // look：查看；edit：编辑; add: 新增; approve:审批
        type: {
            type: String,
            default: "add"
        },
    },
    data() {
        return {
            planName:"",//计划名称
            isProgress:false,//是否列表页点击进入的进展提交
            isStartAct: true, // 是否新建
            fileListDislogVisible: false, //
            rules: [{
                required: true,
                message: '必填项',
                trigger: 'change'
            }],
            fileUploadUrl: process.env.UPDOWN_ROOT,
            showCollapse2: "1",
          showCollapse3:"1",
            showCollapse: "1",
            hasIcon: false,
            loading: false,
            fileList: [],
            fileListDownLoad: [],
            showCollapse1: "1",
            flowDetails: {
                nextActOptions: [],
                approvePerson: [],
                approvePersonId: [],
                activityName: '010',
                isEnd: false,
                actParticipants: {}
            },
            fileProps: [ //文件上传的属性
                {
                    prop: 'fileRealName',
                    label: '文件名'
                },
                {
                    prop: 'createTime',
                    label: '上传时间'
                },
            ],
            flow_access: {
                task_type: '', //任务类型
                mergeTask: '0', //合并任务
                slotCount: '1', //任务处理规则
                resign: '', //会签类型
                reselMan: '', //是否重选快速审批人
                act_name: '', //当前节点名称
                now_deal_act: '010', //当前节点
                deal_answer: '1', //同意 还是退回
                next_deal_act: '', //下一节点
                next_deal_name: [], //下一处理人 [pxmwrya]阮洋  多个
                deal_suggest: '', //审批意见
                copygive: [], //抄送人
                approveMan: '', //当前提交人 自己
                procInstId: '', //流程实例ID
                sn: '', //sn
                backAct: '', //退回节点  020
                backMan: '', //退回人
                procSetId: '', //流程集ID 兑奖流程 463
                fullName: 'BMWS\\TestProcess', //流程全名
                procChName: '', //流程中文名
                procVerId: '',
                isEnd:false,

            },
            planList: [],//计划下拉
            progressList: [],//阶段下拉
            plan:{},//选中的计划
            capaCity:{},//计划详情
            phase:{},//阶段详情
            stage: {
                processName: "",
                phaseId: "",
                // operateType: "1",
            },
             btns: [
               //{
            //         value: 'look',
            //         label: 'cm.look'
            //     },
            //     {
            //         value: 'del',
            //         label: 'cm.delete'
            //     },
              {
                value: 'edit',
                label: 'cm.edit'
              }
            ],
            phaseFileList:[],
            nextObj:{},
             WFConfigActivityList:[],//储存全部节点信息
        }
    },
    computed: {
        ...mapState({
            tableHeaderBGC: state => state.common.tableHeaderBGC
        }),
        edit(){
          const { type } = this;
          return type == 'add' || type == 'edit' || type == 'draftEdit'
        }
    },
    mounted() {
        //获取全部字典
        this.getAllMap();

         //数据初始化
        this.initData();


        if(this.type == 'add'){
             // 从列表页过来的进展提交
            if(this.$router.history.current.params.planName && this.$router.history.current.params.id){
                this.isProgress  = true
                this.capaCity.planName = this.$router.history.current.params.planName;
                this.planName = this.$router.history.current.params.planName;
                this.stage.planId = this.$router.history.current.params.id
                this.getProgressList(this.$router.history.current.params.id)
            }else{
                this.isProgress  = false
                this.getPlanList();
            }

        }
        //不是新增都需要显示详情
        if(this.type != "add" ){
            let id =""
            if(this.type == "approve"){
               id = this.$router.history.current.query.obj.formInstID
               // 待办页面跳过来的拿的进展详情
               this.getProgressInfo(id)
            }else if(this.type == "draftEdit"){
              id = this.$router.history.current.query.obj.formno
              // 草稿跳过来的拿的进展详情
               this.getProgressInfo(id)
            }else if(this.type == "done"){
               id = this.$router.history.current.query.obj.fromNO
               this.getProgressInfo(id)
            }else{
               id = this.$router.history.current.params.id
               //获取年度计划列表
               this.getProgressList(id);
               //获取阶段详情
               this.getProgressDetail(id)
            }
        }
        if(this.type == "approve"){
            this.isStartAct = false;
            this.nextObj = this.$router.history.current.query.obj || {};

            const {
                procInstID,
                showBack,
                backAct,
                backActName,
                backManName,
                backMan,
            } = this.nextObj;


            this.flowDetails = Object.assign({}, this.flowDetails, {
                showBack,
                backAct,
                backMan,
                backActName,
                backManName
            })
            this.flow_access = Object.assign({}, this.flow_access, {
                procInstId:procInstID,
                backAct,
                backMan,
                backManName,
            })
        }

        if(this.type == "draftEdit"){
            this.nextObj = this.$router.history.current.query.obj || {};
            const {
            sourceactmetadata,
            targetactmetadata,
            startuser,
            startusercn,
            id,
            } = this.nextObj
            if(sourceactmetadata === "010"){
            this.isStartAct =true;
            }else{
            this.isStartAct =false;
            }
            this.flow_access.next_deal_act = targetactmetadata;
            let name = `[${startuser}]${startusercn}`;
            this.flow_access.next_deal_name.push(name);
            this.$set(this.flow_access,"draftId",id);
            this.$set(this.flow_access,"next_deal_id",this.nextObj.startuser.split(","));
        }

        if(this.type == "done"){
            this.nextObj = this.$router.history.current.query.obj || {};
            this.flow_access.act_name = this.nextObj.actName;
            this.flow_access.approveMan = `[${this.nextObj.startUser}]${this.nextObj.startCNUser}`;
        }

    },
    methods: {
      dateFormatstart(thistime, fmt) {
        if (!COMMON.isNullOrUndefinedOrSpace(thistime.startTime)) {
          var date = new Date(thistime.startTime)
          var month =date.getMonth()+1;if(month<10){month="0"+month;}
          var day =date.getDate();if(day<10){day="0"+day;}
          var hours =date.getHours();if(hours<10){hours="0"+hours;}
          var min= date.getMinutes();if(min<10){ min="0"+min; }
          var sec= date.getSeconds();if(sec<10){sec="0"+sec;}
          return  date.getFullYear() + '-' + month + '-' + day
        }
        return thistime.startTime
      },
      dateFormatend(thistime, fmt) {
        if (!COMMON.isNullOrUndefinedOrSpace(thistime.endTime)) {
          var date = new Date(thistime.endTime)
          var month =date.getMonth()+1;if(month<10){month="0"+month;}
          var day =date.getDate();if(day<10){day="0"+day;}
          var hours =date.getHours();if(hours<10){hours="0"+hours;}
          var min= date.getMinutes();if(min<10){ min="0"+min; }
          var sec= date.getSeconds();if(sec<10){sec="0"+sec;}
          return  date.getFullYear() + '-' + month + '-' + day
        }
        return thistime.endTime
      },
      handleListBtn({btn,row}){
        if(btn==="edit"){//查看
          this.stage.phaseId =row.id;
          this.getProgressDetail(row.id);
          //console.log(this.capaCity.processName);
          //COMMON.routerTo(Constant.ROUTE_SRI_GAIN_THESIS_LOOK.index, this.$router, { id: row.id })
        }else{//编辑
          //COMMON.routerTo(Constant.ROUTE_SRI_GAIN_THESIS_EDIT.index, this.$router, { id: row.id})
        }
      },
        //获取全部字典
        getAllMap() {
          //   api_sri.sriGainGetBudgetGetAllYear({}, result => {
          //       if (result.code === Constant.RT_SUCCESS) {
          //           this.allYear = result.years
          //       } else {
          //           ALERT.error(result.msg)
          //       }
          //   })

          //   //所在分部
          //   this.sysDictLoadByPaging("budget_belong_subsection",(result)=>{
          //     this.belongSubsecitonMap = result.data
          // })


        },
        //获取字典接口
        sysDictLoadByPaging(key, callback) {
            sys_manage.sysDictLoadByPaging({
                dictGroupKey: key
            }, result => {
                if (result.code === Constant.RT_SUCCESS) {
                    callback(result)
                } else {
                    ALERT.error(result.msg)
                }
            })
        },

        uploadSuccess (res, fileKey) {
          if (res.data && res.data[0]) {
            this.stage.stageResultFileId = res.data[0].fileId
            let file = {name: res.data[0].fileName, url: res.data[0].url, id: res.data[0].fileId}
            this.phaseFileList.push(file)
          }
        },
        uploadRemove (fileList, fileKey) {
          let resList = fileList.map(item => {
            return {
              name: item.name,
              url: item.url,
             id: item.fileId
            }
          })
          this.phaseFileList = resList
          this.stage.stageResultFileId = resList.map(item=>item.id).join(",");
        },
        //选择计划
        planSelectChange(data){
          this.getProgressList(data);
        },
        //选择阶段
        progressSelectChange(data){
          this.getProgressDetail(data);
        },
        //获取计划下拉框列表
        getPlanList(){
          api_sri.sriGainCapacityBuildingGetAllPlanInfo({
          }, result => {

            if (result.code === Constant.RT_SUCCESS) {
                this.planList = result.data;

            } else {
              ALERT.error(result.msg)
            }

          })
        },
        //获取阶段下拉框列表
        getProgressList(planId){
          api_sri.sriGainCapacityBuildingPlanGetPhaseByPlanId({
            planId
          }, result => {
            if (result.code === Constant.RT_SUCCESS) {

                this.stage.phaseId = '';
                this.progress = {};
                this.progressList = result.data;
            } else {
              ALERT.error(result.msg)
            }

          })
        },
        //获取阶段详情
        getProgressDetail(id){
          api_sri.sriGainCapacityBuildingPlanStageInfo({
            id
          }, result => {
            if (result.code === Constant.RT_SUCCESS) {
                const data = result.data || {};
                const {capaCity,phase} = data;
                this.capaCity = capaCity;
                console.log("this.capaCity",this.capaCity);
                this.phase = phase;
                if(this.planName) this.capaCity.planName = this.planName
                const {stageResultFileId,stageResultFileName,stageProgress,stageResultFilePath} = result.data.phase;
                //回填
                this.phaseFileList = stageResultFileId?[{
                    name:stageResultFileName,
                    id:stageResultFileId,
                    url:stageResultFilePath
                }]:[]
                this.$set(this.stage,"stageResultFileId",stageResultFileId?stageResultFileId:"");
                this.$set(this.stage,"stageProgress",stageProgress?stageProgress:"");
                this.$nextTick(()=>{
                    this.$refs.stage.clearValidate();
                })
            } else {
              ALERT.error(result.msg)
            }

          })
        },

         // 待办页面跳过来的拿的进展详情
         getProgressInfo(id){
          api_sri.sriGainGetCapacityBuildingGetPlanProgressInfo({id}, result => {
            if (result.code === Constant.RT_SUCCESS) {
              const data = result.data || {}
                const {capaCity,phase,progress} = data;
                 this.capaCity = capaCity;
                //  this.phase = phase;
                 this.phase = Object.assign({},phase,progress)

                 if(this.type == "draftEdit"){
                     const {stageResultFileId,stageResultFileName,stageProgress,phaseId,stageResultFilePath} = this.phase;
                    //回填
                    this.phaseFileList = stageResultFileId?[{
                        name:stageResultFileName,
                        id:stageResultFileId,
                        url:stageResultFilePath
                    }]:[]
                    this.$set(this.stage,"phaseId",phaseId?phaseId:"");
                    this.$set(this.stage,"stageResultFileId",stageResultFileId?stageResultFileId:"");
                    this.$set(this.stage,"stageProgress",stageProgress?stageProgress:"");
                 }

            } else {
              ALERT.error(result.msg)
            }
          })
        },

        //数据初始化
        initData: function () {
            this.flow_access.procChName = store.state.proc.procName ? store.state.proc.procName : '能力建设年度计划进展审批流程';
            this.flow_access.fullName = 'SWP-SU\\sci_cbpProcess';
            this.flow_access.procSetId = store.state.proc.procSetId;
            this.flow_access.procVerId = store.state.proc.procId;
            this.stage.processName = this.flow_access.procChName;
            //获取最新流程procId
            this.getWFConfigProc({
                fullName: this.flow_access.fullName
            });
        },
        getWFConfigProc(params) { // 获取最新流程procId
            let _this = this;
            getWFConfigProcID(params).then((result) => {
                if (result.status == "200" && result.data.code == "0") {
                    let data = result.data.data || {}
                    _this.flow_access.procSetId = data.procSetID
                    //  审批需要
                    _this.flow_access.procId  = data.procID

                    _this.getSomeInfo(data.procID);
                } else {
                    _this.$alert(result.data.msg, _this.$t('cm.tips'));
                }
            }).catch((err) => {
                _this.$alert(err, _this.$t('cm.tips'));
            });
        },
        getSomeInfo(procVerId) {
          let _this = this;
            //获取全部节点信息
           this.getWFConfigActivityHandle((result)=>{
                //储存全部节点信息
                _this.WFConfigActivityList = result.data.data.data;
                if(this.type=='approve'){
                    //获取流程的开始节点、下一节点还有下一节点处理人
                    let act_metadata_cur = null;
                    //匹配当前节点
                    let d = _this.WFConfigActivityList;//result.data.data.data;
                    for (let i = 0; i < d.length; i++) {
                        if (d[i].actName == _this.nextObj.activityName) {
                            act_metadata_cur = d[i].actMetaData
                        }
                    }

                    //   if(this.nextObj.activityName == "010_项目负责人提交能建计划进展"){
                    //       act_metadata_cur = "010";
                    //   }else if(this.nextObj.activityName == "020_能力建设管理工程师审批") {
                    //       act_metadata_cur = "020";
                    //   }

                    let data = {
                        act_id: this.nextObj.activityID,
                    //   act_metadata: this.nextObj.backAct[0], //这里不能这样判断，backAct不可能是当前环节的act_metadata
                        act_metadata: act_metadata_cur,
                        act_name: this.nextObj.activityName,
                        proc_id: this.nextObj.procID
                    }
                    _this.flow_access.act_name = data.act_name;//当前环节名称
                    _this.flowDetails.activityName = data.act_name;//用于页面显示
                    _this.flow_access.staffNoBefore=this.nextObj.preActivitySender; //上一审批人
                    _this.flow_access.procId = this.nextObj.procID;//提交需要
                    _this.flow_access.actId = this.nextObj.activityID;//提交需要
                    _this.flow_access.now_deal_act  = act_metadata_cur
                    //获取下一处理环节
                    _this.getNextDealNode(data);
                }else{


                        //获取流程的开始节点、下一节点还有下一节点处理人
                        let _this = this;
                        getStartAct(procVerId).then((result) => {
                            if (result.status == "200" && result.data.code == "0") {
                                let data = result.data.data.data;
                                _this.flow_access.act_name = data.act_name; //当前环节名称
                                _this.flowDetails.activityName = data.act_name; //用于页面显示
                                //获取下一处理环节
                                _this.getNextDealNode(data);
                            } else {
                                _this.$alert(result.data.msg, _this.$t('cm.tips'));
                            }
                        }).catch((err) => {
                            _this.$alert(err, _this.$t('cm.tips'));
                        });
                }
           })
        },



        // 保存草稿防抖
        saveDraftHandle:COMMON.debounce('saveProc',500,true),

       // 提交流程防抖
        saveProcHandle:COMMON.debounce('saveProc'),

        // 提交流程
        saveProc(isSaveDraft = false) {
            if(isSaveDraft || this.isStartAct){
               this.addProc(isSaveDraft);
            }else {
                this.purSubmitProcess();
            }
        },
        //添加一个流程
        addProc: function (isSaveDraft) {
            //下一步处理人 设置
            if (document.getElementById("appMan") != null && document.getElementById("appMan").value != "") {
                this.flow_access.next_deal_name = document.getElementById("appMan").value.split(',');
            }
            //判断是否为保存草稿
            if(isSaveDraft){
                this.flow_access.isSaveDraft = "1"; //说明是保存草稿
                this.flow_access.isModifyDraft = this.type === "draftEdit" ? "1" :"0" //编辑草稿
            }else {
                 this.flow_access.isSaveDraft = "0";
            }

            //判断获奖表
            this.$refs['stage'].validate((valid) => {
                if (valid) {
                    if (this.checkValid()) {
                        //设置任务类型、会签规则、会签类型、是否重选快速审批人 http://cudflow-d
                        let selNextAct = this.flowDetails.nextActOptions.find(n => {
                            return (n.actMetadata == this.flow_access.next_deal_act);
                        })

                        this.flow_access.task_type = selNextAct.taskActType;
                        this.flow_access.mergeTask = selNextAct.isMergeTask;
                        this.flow_access.slotCount = selNextAct.taskProcessRule;
                        this.flow_access.resign = selNextAct.reSignType;
                        this.flow_access.reselMan = selNextAct.isReselFastDealer;

                        //设置关联文件
                        this.flow_access.fileList = this.fileListDownLoad;

                        let _this = this;

                        this.flow_access.stage = this.stage;

                        api_sri.sriGainCapacityBuildingPlanStageSave(this.flow_access, result => {
                            if (result.code === Constant.RT_SUCCESS) {
                                ALERT.success(result.msg)
                                if(isSaveDraft){
                                    _this.$router.push(Constant.ROUTE_MYDRAFT.index);
                                }else{
                                     _this.$router.push(Constant.ROUTE_ALREADY_DONE_TASK.index);
                                }
                            } else {
                                ALERT.success(result.msg)
                            }
                        })
                    }
                } else {
                    return false;
                }
            })
        },
        getNextDealNode: function (data) { //获取下一节点 通过 下一步点处理人接口
            let _this = this;
             let procInstId = this.type=='approve' ? _this.nextObj.procInstID :0;
            let params = {
                actId: data.act_id,
                procInstId,
                procId: data.proc_id,
                node: data.act_metadata,
            }
            getNextApprovePerson(params).then((result) => {
                if (result.status == "200" && result.data.code == "0") {
                    let data = result.data.data.data;
                    this.getNextNodeInfo(data);
                } else {
                    _this.$alert(result.data.msg, _this.$t('cm.tips'));
                }
            }).catch((err) => {
                _this.$alert(err, _this.$t('cm.tips'));
            });
        },
        //获取全部节点信息
        getWFConfigActivityHandle(calback){
            let _this = this;
            let params = {
                fullName: this.flow_access.fullName,
                procSetId: "", //this.flow_access.procSetId
            };
            getWFConfigActivity(params).then((result) => {
                if (result.status == "200" && result.data.code == "0") {
                    calback(result)
                } else {
                    _this.$alert(result.data.msg, _this.$t('cm.tips'));
                }
            }).catch((err) => {
                _this.$alert(err, _this.$t('cm.tips'));
            });

        },
        //获取下一节点详情
        getNextNodeInfo: function (data) {
            //获取流程配置中的流程节点信息  可以存储在store中getBpmPscActInfo
            let _this = this;
            //存在多个下一环节的情况
            console.log('存在多个下一环节的情况', data)
            for (const metadata in data) {
                let d = _this.WFConfigActivityList;//result.data.data.data;
                for (let i = 0; i < d.length; i++) {
                    if (d[i].actMetaData == metadata) {
                        _this.flowDetails.actParticipants[metadata] = data[metadata];
                        _this.getNextNodeDetails(d[i]);
                    }
                }
            }
        },


        // 审批流程
        purSubmitProcess () {

             //抄送人
          if(document.getElementById("sendToMan")!= null && document.getElementById("sendToMan").value != ""){
              this.flow_access.copygive = document.getElementById("sendToMan").value.split(',');
          }

          //下一步处理人
          if(this.flow_access.participantSelectRestlt) {
              let value = [];
              let parts = this.flow_access.participantSelectRestlt.split(",");
              for(let i = 0; i < parts.length; i++){
                  value.push(parts[i]);
              }
              this.flow_access.next_deal_name = value;
          }
         if(this.checkValid()){
                //设置任务类型、会签规则、会签类型、是否重选快速审批人 http://cudflow-d
                let selNextAct = this.flowDetails.nextActOptions.find(n =>{
                    //   return (n.actMetadata == this.flow_access.next_deal_act);
                    return true;
                })

                // this.flow_access.act_name = selNextAct.actName;//当前环节名称
                // this.flow_access.actId = selNextAct.actId;//当前环节Id
                this.flow_access.act_name = this.nextObj.activityName;//当前环节名称
                this.flow_access.actId = this.nextObj.activityID;//当前环节Id
                this.flow_access.task_type = selNextAct.taskActType;
                this.flow_access.mergeTask = selNextAct.isMergeTask;
                this.flow_access.slotCount = selNextAct.taskProcessRule;
                this.flow_access.resign = selNextAct.reSignType;
                this.flow_access.reselMan = selNextAct.isReselFastDealer;
                this.flow_access.auditNote = this.flow_access.deal_suggest;
                this.flow_access.formInstID = this.nextObj.formInstID;
                this.flow_access.procInstId = this.nextObj.procInstID;
                    this.flow_access.sn = this.nextObj.sn;

                //处理回退逻辑
                this.flow_access.backAct = this.nextObj.backAct[0];
                this.flow_access.backMan = this.nextObj.backMan[0];
                this.flow_access.backManName = this.nextObj.backManName[0];

                //设置关联文件
                this.flow_access.fileList = this.fileListDownLoad;
                let _this = this;
                api_sri.sriGainCapacityBuildingPlanStageSubmitProcess(this.flow_access, result => {
                    if (result.code === Constant.RT_SUCCESS) {
                    ALERT.success(result.msg)
                    _this.$router.push(Constant.ROUTE_ALREADY_DONE_TASK.index);
                    } else {
                    ALERT.success(result.msg)
                    }
                })
         }
        },


        //获取下一节点详细信息
        getNextNodeDetails(arr) {
            let _this = this;
            getBpmPscActInfo({
                actId: arr.actID
            }).then((result) => {
                if (result.status == "200" && result.data.code == "0") {
                    let data = result.data.data.data;
                    //获取下一步点处理人
                    console.log('获取下一步点处理人', data)
                    _this.flowDetails.nextActOptions.push(data);
                } else {
                    _this.$alert(result.data.msg, _this.$t('cm.tips'));
                }
            }).catch((err) => {
                _this.$alert(err, _this.$t('cm.tips'));
            });

        },
        //统一用户格式
        unifyUser: function (users) {
            for (let i = 0; i < users.length; i++) {
                if (typeof (users[i].item_principal_desc) != "undefined" && typeof (users[i].item_principal_desc) != null) {
                    this.flowDetails.approvePerson.push("[" + users[i].item_principal + "]" + users[i].item_principal_desc);
                    this.flowDetails.approvePersonId.push(users[i].item_principal);
                }
            }
        },
        //上传文件时的回调
        upfileBack: function (response, file, fileList) {
            this.loading = false;
            if (response.code == "0") {
                this.fileListDownLoad.push(response.data);
            } else {
                this.$alert(response.msg, this.$t('cm.tips'));
            }
        },
        //上传文件之前的处理
        beforeUpload: function (file) {
            //在这里进行上传文件的设置
            let type = file.name.substring(file.name.lastIndexOf('.') + 1);
            const limitSize = file.size / 1024 / 1024 < 10; //文件大小限制
            if (!limitSize) {
                this.$alert("上传文件大小不能超过10M", this.$t('cm.tips'));
            }
            return limitSize;
        },
        loadingFile: function () {
            this.loading = true;
        },
        uplofileError: function () {
            this.loading = false;
        },
        //删除文件
        delFiles: function (row) {
            let _this = this;
            delFile({
                fileId: row.fileId
            }).then((result) => {
                if (result.status == "200" && result.data.code == "0") {
                    _this.fileListDownLoad.splice(_this.fileListDownLoad.findIndex(item => item.fileId === row.fileId), 1);
                } else {
                    _this.$alert(result.data.msg, _this.$t('cm.tips'));
                }
            }).catch((err) => {
                _this.$alert(err, _this.$t('cm.tips'));
            });
        },
         checkValid() {
            if (!this.flow_access.deal_answer) {
                this.$alert("请选择处理结论!", this.$t('cm.tips'));
                return false;
            } else if (!this.flow_access.next_deal_act) {
                this.$alert("请选择下一环节!", this.$t('cm.tips'));
                return false;
            } else if (!this.flow_access.isEnd&&this.flow_access.deal_answer==1&&this.flow_access.next_deal_name.length == 0) {
                this.$alert("请选择下一步处理人", this.$t('cm.tips'));
                return false;
            } else {
                return true;
            }
        },
        addFileListDislog() {
            this.fileListDislogVisible = true
        },
        closeFileListDislog() {
            this.fileListDislogVisible = false
        },
        addFileList(data) {
            this.stage.purchaseContractItemList = data
            this.fileListDislogVisible = false
        },

    },
    watch: {

    },
    filters:{
     dateFormatType(data) {
        //console.log("timedata--1065--"+data);
        if (!COMMON.isNullOrUndefinedOrSpace(data)) {
              var date = new Date(data)
              var month =date.getMonth()+1;if(month<10){month="0"+month;}
              var day =date.getDate();if(day<10){day="0"+day;}
              var hours =date.getHours();if(hours<10){hours="0"+hours;}
              var min= date.getMinutes();if(min<10){ min="0"+min; }
              var sec= date.getSeconds();if(sec<10){sec="0"+sec;}

            return  date.getFullYear() + '-' + month + '-' + day
        }
            return data
      }

  },

}
</script>

<style lang="scss">
.abp-progress-details{
  .el-form-item__content>span:empty:before{
    content:"--"
  }
}
</style>
